package com.module.frame.base

import android.os.Bundle
import android.view.View
import androidx.annotation.CallSuper
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

/**
 * 主要处理BaseViewModel 根据泛型创建
 */
abstract class BaseVmActivity<VM : BaseFrameViewModel> : AppBaseActivity() {

    lateinit var mViewModel: VM

    /**
     * 绑定ViewModel
     */
    abstract fun bingViewModel()

    abstract fun getLayoutView(): View?

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    @CallSuper
    override fun initView() {
        //vm初始化
        mViewModel = createViewModel()
        bingViewModel()
    }

    /**
     * 重载，不使用父类的设置试图，而是使用 getLayoutView
     */
    override fun setContentView() {
        var layoutView = getLayoutView();
        if (layoutView != null) {
            setContentView(layoutView)
        } else {
            setContentView(getLayoutId())
        }
    }

    /**
     * 创建viewModel
     */
    private fun createViewModel(): VM {
        return try {
            val mClass =
                (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
            ViewModelProvider(this).get(mClass)
        } catch (e: Exception) {
            BaseFrameViewModel() as VM
        }
    }

}